package tx.plus;

import lombok.Getter;
import lombok.SneakyThrows;

import javax.sql.DataSource;
import java.io.PrintWriter;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Proxy;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.SQLFeatureNotSupportedException;
import java.util.logging.Logger;

public class PlusDataSource implements DataSource {

    private final Constructor<? extends Connection> lazyConnectionConstructor;
    @Getter
    private final DataSource dataSource;

    @SneakyThrows
    public PlusDataSource(DataSource dataSource) {
        this.dataSource = dataSource;

        Connection connection = (Connection) Proxy.newProxyInstance(getClass().getClassLoader(), new Class[]{Connection.class}
                , new ConnectionHandler(null));
        lazyConnectionConstructor = connection.getClass()
                .getConstructor(InvocationHandler.class);
    }

    @Override
    @SneakyThrows
    public Connection getConnection(String username, String password) throws SQLException {
        return  lazyConnectionConstructor.newInstance(new ConnectionHandler(dataSource,username,password));
    }

    @SneakyThrows
    @Override
    public Connection getConnection() throws SQLException {
        return  lazyConnectionConstructor.newInstance(new ConnectionHandler(dataSource));
    }

    @Override
    public PrintWriter getLogWriter() throws SQLException {
        return dataSource.getLogWriter();
    }

    @Override
    public void setLogWriter(PrintWriter out) throws SQLException {
        dataSource.setLogWriter(out);
    }

    @Override
    public void setLoginTimeout(int seconds) throws SQLException {
        dataSource.setLoginTimeout(seconds);
    }

    @Override
    public int getLoginTimeout() throws SQLException {
        return dataSource.getLoginTimeout();
    }

    @Override
    public Logger getParentLogger() throws SQLFeatureNotSupportedException {
        return dataSource.getParentLogger();
    }

    @Override
    public <T> T unwrap(Class<T> iface) throws SQLException {
        return dataSource.unwrap(iface);
    }

    @Override
    public boolean isWrapperFor(Class<?> iface) throws SQLException {
        return dataSource.isWrapperFor(iface);
    }

}
